#include "rcvdata.h"
#include "jlog.h"

QVector<int> ZeroValue;
QVector<int> FullValue;
extern int CollectType;  // 1:连续采集;2:触发采集
extern int Frequency;
extern int TimeLength;
extern int VoltageLevel;
extern bool IsCollect;
extern int TriggerMode;

RcvData::RcvData(QObject *parent) : QObject(parent)
{
    Init();
}

RcvData::RcvData(QTcpSocket *Sock)
{
    Init();
    SockData = Sock;
    connect(SockData, SIGNAL(connected()), this, SLOT(SlotConnect()), Qt::DirectConnection);
    connect(SockData, SIGNAL(disconnected()), this, SLOT(SlotDisconnect()), Qt::DirectConnection);
    connect(SockData, SIGNAL(error(QAbstractSocket::SocketError)), this, SLOT(SlotErr(QAbstractSocket::SocketError)), Qt::DirectConnection);
    connect(SockData, SIGNAL(readyRead()), this, SLOT(SlotReadData()), Qt::DirectConnection);
}

void RcvData::Init()
{
    RcvCnt = 0;
    RcvTimer = new QTimer;
    connect(RcvTimer, SIGNAL(timeout()), this, SLOT(RcvTimerOut()));
}

void RcvData::CloseScoket()
{
    SockData->disconnectFromHost();
    SockData->close();
    SockData->deleteLater();
}

//************************事件*************************************
void RcvData::SlotConnect()
{
    qDebug() << "data-connect successful!";
    emit ConnectRight();
}

void RcvData::SlotErr(QAbstractSocket::SocketError err)
{
    qDebug() << "data-connect error:" << err;
    emit ConnectError();
}

void RcvData::SlotDisconnect()
{
    qDebug() << "data-disconnect!";
}

void RcvData::SlotReadData()
{
    if(!IsCollect)
        return;
    emit SendData(SockData->readAll());
//    qDebug() << QDateTime::currentDateTime().toString("yyyy-MM-dd hh:mm:ss.zzz");
#if 0
    // 如果当前的数据小于1024则等待下一次读取
    while(SockData->bytesAvailable() < BYTESUM)
        SockData->waitForReadyRead();
    if(TriggerMode == 13) {
        QDir dir("/mnt/Sync");
        if(!dir.exists()) {
            dir.mkpath("/mnt/Sync");
        }
    }
    if(RcvTimer->isActive())
        RcvTimer->stop();
    RcvTimer->start(3000); // 3s timeout
    char DataBuf[BYTESUM];
    unsigned int ReadLen;
    memset(DataBuf, 0, BYTESUM);
    if((ReadLen = SockData->read(DataBuf, BYTESUM)) <= 0)
        return;
    JLog log;
    log.WriteLog("[DATA] Receive data, data len:" + QString::number(ReadLen));
    emit SendData((unsigned char*)DataBuf);
#endif
}

void RcvData::RcvTimerOut()
{
    // timer stop, just exec once
    RcvTimer->stop();
    // 判断是否存在保存同步数据文件的同步文件夹，存在重命名
    if(TriggerMode == 13) {
        QDir dir("/mnt/Sync");
        if(!dir.exists()) {
            dir.mkpath("/mnt/Sync");
        }
        else {
            QDateTime dt = QDateTime::currentDateTime();
            dir.rename("/mnt/Sync", "/mnt/Sync_" + dt.toString("yyyyMMddhhmmss"));
            dir.mkpath("/mnt/Sync");
        }
    }
}
